package com.kx.base.result;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * 封装rest api 的返回结果类型
 * 这个类是通用的返回结果
 * 这个类要支持链式编程
 *
 * @Author Sun
 * @Date 2021/7/16 17:46
 */
public class R {
    int code;
    String msg;
    Object result;
    public static final int OK_200=200;
    public static final int E_500=500;
    private static final int IS_OK=100;
    public boolean isOK(){
        if(this.code/IS_OK==2){
            return true;
        }
        return false;
    }
    /**
     * 调用成功的方法
     */
    public static R ok() {
        R r = new R().setCode(200).setMsg("请求成功");
        return r;
    }

    public static R ok(int code) {
        R r = new R().setCode(code).setMsg("请求成功");
        return r;
    }

    public static R ok(String msg) {
        R r = new R().setCode(200).setMsg(msg);
        return r;
    }

    public static R ok(int code, String msg) {
        R r = new R().setCode(code).setMsg(msg);
        return r;
    } public static R ok(Object data,int code, String msg) {
        R r = new R().setResult(data).setCode(code).setMsg(msg);
        return r;
    }

    public static R ok(Object data) {
        return ok().setResult(data);
    }

    /**
     * 调用失败的方法
     */
    public static R error() {
        R r = new R().setCode(500).setMsg("请求失败");
        return r;
    }

    public static R error(int code) {
        R r = new R().setCode(code).setMsg("请求失败");
        return r;
    }

    public static R error(String msg) {
        R r = new R().setCode(500).setMsg(msg);
        return r;
    }

    public static R error(int code, String msg) {
        R r = new R().setCode(code).setMsg(msg);
        return r;
    }

    public static R error(Object data) {
        return error().setResult(data);
    }

    /**
     * r对象转Json的方法
     */
    public String toJsonString(R r){
        return JSONObject.toJSONString(r);
    }


    /**
     * 让所有的set方法都返回当前对象this
     * 支持链式编程
     */
    public R setCode(int code) {
        this.code = code;
        return this;
    }

    public R setResult(Object result) {
        this.result = result;
        return this;
    }

    /**
     * 封装返回集合类型数据的方法
     */
    public R setResult(String key,Object value){
        if(result==null){
            JSONObject result=new JSONObject();
            result.put(key,value);
            this.result=result;
        }else{
            if(result instanceof JSONObject){
                ((JSONObject)result).put(key,value);
            }
            if(result instanceof Map){
                ((Map)result).put(key,value);
            }
        }
        return this;
    }

    public R setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public Object getResult() {
        return result;
    }

    @Override
    public String toString() {
        return toJsonString(this);
    }
}
